package org.adream.dreamnt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WeixinUtil {
	private static Logger logger = LoggerFactory.getLogger(WeixinUtil.class);

	public static String getAccess_token(String url) {
		String accessToken = null;
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); //
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			accessToken = new String(jsonBytes, "UTF-8");
			is.close();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return null;
		}

		return accessToken;
	}
	
	public static String httpGet(String url) throws ClientProtocolException, IOException {
		CloseableHttpClient httpclient = null;
		InputStream is = null;
		BufferedReader reader = null;
		try{
			httpclient = HttpClientBuilder.create().build();
			HttpGet hg = new HttpGet(url);
			CloseableHttpResponse r = httpclient.execute(hg);
			HttpEntity he = r.getEntity();
			is = he.getContent();
			reader = new BufferedReader(new InputStreamReader(is));
			String str = "";
			String line = "";
			while ((line = reader.readLine()) != null) {
				str = str + "\n" + line;
			}
			return str;
		}finally{
			try{
				if(reader!=null)
					reader.close();
			}catch(Exception e){
				logger.warn(e.getMessage(),e);
			}
			try{
				if(is!=null)
					is.close();
			}catch(Exception e){
				logger.warn(e.getMessage(),e);
			}
			try{
				if(httpclient!=null)
					httpclient.close();
			}catch(Exception e){
				logger.warn(e.getMessage(),e);
			}
		}
	}
}